import { Action, ActionReducer, combineReducers } from "@ngrx/store";
import { List } from "immutable";
import { environment } from "../../environments/environment";
import { compose } from "@ngrx/core";
import { storeFreeze } from "ngrx-store-freeze";
import { Todo, TODOS } from "./model/todo";
import { ADD_TODO, COMPLETE_TODO, DELETE_TODO, FILTER_ACTIONS, FILTER_ALL } from "./actions";

export interface State {
  todos: {},
  filterTodo: () => true
}

export const todos = (state: List<Todo> = TODOS, { type, payload }: Action) => {
  switch (type) {
    case ADD_TODO:
      return state.push(<Todo>payload.set('id', state.size + 1))

    case COMPLETE_TODO:
      return state.map(todo => {
        return todo.id !== payload.id ? todo : todo.set('completed', true)
      })

    case DELETE_TODO:
      return state.filter(todo => todo.id !== payload.id)
  }
  return state
}

export const filterTodo = (state = 'All', { type }: Action) => {
  switch (type) {
    case FILTER_ACTIONS.All:
      return 'All'
    case FILTER_ACTIONS.Complete:
      return 'Complete'
    case FILTER_ACTIONS.Pending:
      return 'Pending'
  }
  return state
}

const reducers = {
  todos,
  filterTodo
}

const developmentReducer: ActionReducer<State> = compose(storeFreeze, combineReducers)(reducers)
const productionReducer: ActionReducer<State> = combineReducers(reducers)

export function reducer(state, action) {
  if (environment.production) {
    return productionReducer(state, action)
  } else {
    return developmentReducer(state, action)
  }
}
